package com.homework;

import com.homework.bean.ConsumerComponent;
import com.homework.util.ReportStatus;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ConsumerBoot {
    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
        context.start();
        //输出运行结果
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new ReportStatus(), 5,5, TimeUnit.SECONDS);

        ConsumerComponent service = context.getBean(ConsumerComponent.class);

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 100, 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));
        long startTime = System.currentTimeMillis();
        int minutes = 3;
        int count = 0;
        while (true) {
            try {
                // 休眠5ms防止线程池满
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                threadPoolExecutor.execute(() -> {
                    service.aMethod();
                });
                threadPoolExecutor.execute(() -> {
                    service.bMethod();
                });
                threadPoolExecutor.execute(() -> {
                    service.cMethod();
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            count++;
            // 执行三分钟结束
            if ((System.currentTimeMillis() - startTime) > minutes * 60 * 1000) break;
        }
        System.out.println("平均每分钟调用 - " + count / minutes + " - 次");

    }

    @Configuration
    @PropertySource("classpath:/dubbo-consumer.properties")
    @ComponentScan("com.homework.bean")
    @EnableDubbo()
    static class ConsumerConfiguration {

    }
}
